﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.IO;
using MapEntities;
using VirtualEarth.Business;
using System.Windows.Browser;

namespace VirtualEarth
{
    public partial class MainPage : UserControl
    {
        private string requestID = null;
        private string pageUri = null;
        private MapVisualizer visualizer = null;
        public MainPage()
        {
            InitializeComponent();
        }

        public MainPage(string requestID, string pageUri)
            : this()
        {
            this.requestID = requestID;
            this.pageUri = pageUri;
            InitMap();
        }

        private void InitMap()
        {
            map.Loaded += new RoutedEventHandler(map_Loaded);
        }

        void map_Loaded(object sender, RoutedEventArgs e)
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            string url = Application.Current.Host.Source.AbsoluteUri.Replace(Application.Current.Host.Source.Query, "");
            if (!string.IsNullOrEmpty(pageUri))
            {
                Uri newUrl = new Uri(pageUri);
                string t1 =string.IsNullOrEmpty(newUrl.Query) ? newUrl.AbsoluteUri : newUrl.AbsoluteUri.Replace(newUrl.Query, "");                
                string res = t1.Remove(t1.LastIndexOf('/') + 1, t1.Length - (t1.LastIndexOf('/') + 1));
                res = res + "map.axd";
                url = res;
            } 


           
            url += "?RequestID=" + requestID + "&t=result&uri=" + HttpUtility.UrlEncode(pageUri) + "&Rand=" + new Random().Next();
            client.DownloadStringAsync(new Uri(url));
            map.Visibility = Visibility.Collapsed;
        }

        void ShowError(string xerror)
        {
            RowDefinition xr0 = new RowDefinition();
            xr0.MaxHeight = 16;
            RowDefinition xr1 = new RowDefinition();
            LayoutRoot.RowDefinitions.Add(xr0);
            LayoutRoot.RowDefinitions.Add(xr1);
            TextBlock xtb = new TextBlock();
            xtb.Text = xerror;
            Grid.SetRow(xtb, 0);
            LayoutRoot.Children.Add(xtb);
            map.SetValue(Grid.RowProperty, 1);
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                XmlSerializer serializer = new XmlSerializer(typeof(MapDataResult));
                StringReader reader = new StringReader(e.Result);

                MapDataResult result = (MapDataResult)serializer.Deserialize(reader);

                reader.Close();

                BindMap(result);
            }
            else
            {
                ShowError(e.Error.Message.ToString());
            }
            map.Visibility = Visibility.Visible;
        }

        private void BindMap(MapDataResult result)
        {
            visualizer = new MapVisualizer(map, result);
            try
            {
                visualizer.Visualize();
            }
            catch (Exception exc)
            {
                ShowError(exc.Message.ToString());
            }
        }
    }
}
